package site.teamo.biu.net.server.core.http_https_proxy;

import io.netty.channel.Channel;
import site.teamo.biu.net.common.util.HostPort;
import site.teamo.biu.net.server.core.http_https_proxy.client.DirectTransferClient;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author haocongshun
 * @date 2023/06/13 16:56:58
 */
public class ConnectionHandler {
    private Map<String, DirectTransferClient> clients;

    private final TrafficStatistics trafficStatistics;

    public ConnectionHandler(TrafficStatistics trafficStatistics) {
        this.trafficStatistics = trafficStatistics;
        this.clients = new ConcurrentHashMap<>();
    }

    public void httpHttps(String clientId, HostPort hostPort, Channel channelFromProxyClient) {
        DirectTransferClient client = clients.getOrDefault(clientId, new DirectTransferClient(trafficStatistics.getIn(), trafficStatistics.getOut()));
        client.direct(hostPort, channelFromProxyClient);
    }

    public void close() {
        this.clients.values()
                .forEach(DirectTransferClient::close);
        this.clients.clear();
    }
}
